package cn.tedu.weibo.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //通过请求对象可以获取会话对象session
        HttpSession session=request.getSession();
        //User user=(User)session.getAttribute("user");

        if(session.getAttribute("user")!=null){
            return true;//可以通过
        }
        else {
            //如果该请求被拦截，我们需要对响应对象进行设置，否则浏览器得不到任何响应内容
            //例如：用户没有登录时，要求浏览器请求首页
            response.sendRedirect("/index.html");
            return false;//拦截请求
        }


        //根据session中是否存在登录用户信息决定是否进行拦截
        //return session.getAttribute("user")!=null;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
